#include <pthread.h>

#include "commom_func.h"


/*****************************************************************************
 Prototype    : setSocketAttr
 Description  : 设置socket属性
 Input        : None
 Output       : None
 Return Value : int

  History        :
  1.Date         : 2016/7/8
    Author       : wuquanwei
    Modification : Created function

*****************************************************************************/
int setSocketAttr(int iFd)
{
    int flag=1;

    struct linger so_linger;

    setsockopt(iFd,IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));

#if 1  //֢o̹֮Ӕԃ֢ז׽ʽì׸һˇԃ؇بɻք׽ʽìˇӲΪ؇بɻքsocketַԃconnectʱìԦm҈ޏé׳
    struct timeval tv;
    tv.tv_sec  = SOCKET_SEND_RECV_TIMEOUT_SEC;
    tv.tv_usec = SOCKET_SEND_RECV_TIMEOUT_USEC;
    //sendע̍Ӭʱʱݤ
    setsockopt(iFd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));

    tv.tv_sec  = 5; //connectlޓӬʱ׵ܘքʱݤ
    tv.tv_usec = 0;
    setsockopt(iFd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
#else
    setObjectFdNoblock(iFd);
#endif

    so_linger.l_onoff = 1;
    so_linger.l_linger = 0;
    setsockopt(iFd,SOL_SOCKET,SO_LINGER,(char*)&so_linger,sizeof(so_linger));

    return 0;
}

/*****************************************************************************
 Prototype    : setObjectFdNoblock
 Description  : 设置socket属性为非阻塞
 Input        : None
 Output       : None
 Return Value : void

  History        :
  1.Date         : 2016/7/8
    Author       : wuquanwei
    Modification : Created function

*****************************************************************************/
int setObjectFdNoblock(int iFd)
{
    int opts;

    opts = fcntl(iFd, F_GETFL);
    if (opts < 0)
    {
       perror("fcntl(sock,GETFL)");
    }

    opts = opts | O_NONBLOCK;
    if (fcntl(iFd, F_SETFL, opts) < 0)
    {
       perror("fcntl(sock,SETFL,opts)");
    }

    return opts;
}




/*
*设置超时，使用select
*/
int readable_timeo(int fd, int sec)
{
	fd_set rset;
	struct timeval	tv;

	FD_ZERO(&rset);
	FD_SET(fd, &rset);

	tv.tv_sec = sec;
	tv.tv_usec= 0;

	return(select(fd+1, &rset, NULL, NULL, &tv));
	/*> 0 有文件描述符可读， =0 超时 < 0 无描述符可读*/
}

//创建分离线程
int creat_pthreat(pthread_t* tidp, void*(*start_rtn)(void*),void * arg)
{
    int ret = -1;
    pthread_attr_t attr;
	/*初始化属性值，分离状态*/
	pthread_attr_init(&attr);
	/*PTHREAD_CREATE_DETACHED（分离线程）和 PTHREAD _CREATE_JOINABLE（非分离线程）*/
	pthread_attr_setscope(&attr, PTHREAD_CREATE_DETACHED);

	ret = pthread_create(tidp, &attr,  start_rtn, arg);//
    if(ret < 0)
    {
        perror("#[av]: creat connect_to_av error!");
    }
	usleep(1000*20); //20ms

    return ret;
}



















